'''
Created on 04/03/2009

@author: eh01
'''

from dao.hubUserDAO import HubUserDAO
from dao.nodeDAO import NodeDAO
from domain.hubuser import HubUser
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from logindecorator import adminLoginRequired
from google.appengine.api import memcache
import os

class CurrentlyConnectedNodesRequestHandler(webapp.RequestHandler):
    @adminLoginRequired
    def get(self):
        nodeDAO = NodeDAO()
        nodes = nodeDAO.getCurrentlyConnectedNodes()
        path = os.path.join(os.path.dirname(__file__), '../template/currentlyconnectednodes.html')
        self.response.out.write(template.render(path, {'nodes':nodes}))

class LastConnectedNodesRequestHandler(webapp.RequestHandler):
    @adminLoginRequired
    def get(self):
        nodeDAO = NodeDAO()
        nodes = nodeDAO.getAllNodes()
        path = os.path.join(os.path.dirname(__file__), '../template/lastconnectednodes.html')
        self.response.out.write(template.render(path, {'nodes':nodes}))        

class AdminHomeRequestHanlder(webapp.RequestHandler):
    @adminLoginRequired
    def get(self):
        path = os.path.join(os.path.dirname(__file__), '../template/admin.html')
        self.response.out.write(template.render(path, {}))        
    
class FlushMemcacheRequestHandler(webapp.RequestHandler):
    @adminLoginRequired
    def post(self):
        number_of_items_to_be_flushed = 0
        if memcache.get_stats():
            number_of_items_to_be_flushed = memcache.get_stats()['items']
            memcache.flush_all()
        path = os.path.join(os.path.dirname(__file__), '../template/flushmemcacheconfirmation.html')
        self.response.out.write(template.render(path, {'number_of_items_flushed':number_of_items_to_be_flushed}))  
        
application = webapp.WSGIApplication([('/admin/node-last-connected', LastConnectedNodesRequestHandler),
                                      ('/admin/node', CurrentlyConnectedNodesRequestHandler),
                                      ('/admin/flush-memcache', FlushMemcacheRequestHandler),
                                      ('/admin', AdminHomeRequestHanlder)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()        